//
//  MBDTextViewEditCell.swift
//  
//
//  Created by kyson on 2023/10/25.
//

import Foundation

import UIKit
import YYText


class MBDTextViewEditCell: MBDCommonCell,UITextViewDelegate {
    var infoEditTextView : UITextView!
    var tipsLabel : YYLabel!
    private var isLocationToEnd: Bool = false

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.initialize()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        self.initialize()
    }
    
    override var cellModel: Any! {
        didSet {
            let realCellModel = self.cellModel as! MBDModifyInfoTextViewEditCellModel
            realCellModel.cellWillDisplayBlock =  { ()->Void in
                self.infoEditTextView.becomeFirstResponder()
            }
            self.infoEditTextView.text = realCellModel.text
            self.updateTips()

            self.tipsLabel.text = String(format: "%d",realCellModel.textLimit ?? 0)
        }
    }
    
    func initialize() {
        infoEditTextView = UITextView()
        infoEditTextView.delegate = self

        infoEditTextView.font = UIFont.systemFont(ofSize: 16)
        self.commonBackgroundView.addSubview(infoEditTextView)
        
        let tipsBackgroundView = UIView()
        tipsBackgroundView.backgroundColor = UIColor(colorHex: 0xF4F4F4)
        self.commonBackgroundView.addSubview(tipsBackgroundView)
        
        tipsLabel = YYLabel()
        tipsLabel.textColor = UIColor.gray
        tipsLabel.font = UIFont.systemFont(ofSize: 12)
        tipsLabel.textAlignment = .right
        self.commonBackgroundView.addSubview(tipsLabel)
        tipsBackgroundView.snp.makeConstraints { make in
            make.top.equalTo(infoEditTextView.snp.bottom)
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        tipsLabel.snp.makeConstraints { make in
            make.edges.equalTo(tipsBackgroundView)
        }
        
        infoEditTextView.snp.makeConstraints { make in
            make.left.equalTo(self.commonBackgroundView)
            make.top.equalTo(self.commonBackgroundView)
            make.bottom.equalTo(self.commonBackgroundView).offset(-36)
            make.right.equalTo(self.commonBackgroundView)
        }

    }
    
    
    private func updateTips(){
        let realCellModel = self.cellModel as! MBDModifyInfoTextViewEditCellModel

        if let realText = realCellModel.text {
            tipsLabel.text = String(realCellModel.textLimit! - realText.count)
        }
        
        if Int(tipsLabel.text!) ?? 0 > 0 {
            tipsLabel.textColor = UIColor.gray
        } else {
            tipsLabel.textColor = UIColor.red
        }
    }
    
    func textViewDidChange(_ textView: UITextView) {
        let realCellModel = self.cellModel as! MBDModifyInfoTextViewEditCellModel
        realCellModel.text = textView.text
        
        self.updateTips()
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "" { // 删除字数
            return true
        }
        let realCellModel = self.cellModel as! MBDModifyInfoTextViewEditCellModel
        let maxWordsCount = realCellModel.textLimit!
            
        let inputMode = UITextInputMode.activeInputModes.first?.primaryLanguage
        if inputMode == "zh-Hans" || inputMode == "zh-Hant" { // 简体/繁体中文输入法(拼音、手写输入等)
            if let selectedRange = textView.markedTextRange,
                let _ = textView.position(from: selectedRange.start, offset: 0) { // 如果有高亮的文本，如拼音、手写
                // 拼音输入：联想的过程中，location时刻变化(高亮文本的尾部位置)，length始终为0
                // 手写输入：联想的过程中不会回调该代理方法，确认联想词后才会进入该代理方法
                if range.length > 0 { // 选中联想词后，location变回高亮文本的起始位置，length为高亮文本的长度，需要对字数限制字数
                    return !limitMaxWordsCount(textView, replacementText: text, isLocationToEnd: false)
                }
            } else { // 没有高亮选择的字，对已输入的文字进行字数限制
                if range.location >= maxWordsCount {
                    self.tipsLabel.textColor = UIColor.red
                    self.tipsLabel.text = "0"
                    return false
                } else { // 处理粘贴引起的字数超限, 截取文本后需要自己去移动光标到尾部
                    return !limitMaxWordsCount(textView, replacementText: text, isLocationToEnd: true)
                }
            }
        } else { // 中文输入法以外的输入法直接进行字数限制
            if range.location >= maxWordsCount {
//                SVProgressHUD.showError(withStatus: "最多可输入\(maxWordsCount)字")
                self.tipsLabel.textColor = UIColor.red
                self.tipsLabel.text = "0"
                return false
            } else { // 处理粘贴引起的字数超限, 截取文本后需要自己去移动光标到尾部
                return !limitMaxWordsCount(textView, replacementText: text, isLocationToEnd: true)
            }
        }
            
        return true
    }
    
    func textViewDidChangeSelection(_ textView: UITextView) {
        let realCellModel = self.cellModel as! MBDModifyInfoTextViewEditCellModel
        let maxWordsCount = realCellModel.textLimit!
        
        if let text = textView.text, isLocationToEnd, text.utf16.count >= maxWordsCount {
            textView.selectedRange = NSRange(location: maxWordsCount, length: 0)
            isLocationToEnd = false
        }
    }
    
    func limitMaxWordsCount(_ textView: UITextView, replacementText text: String, isLocationToEnd: Bool) -> Bool {
        let realCellModel = self.cellModel as! MBDModifyInfoTextViewEditCellModel
        let maxWordsCount = realCellModel.textLimit!
        
        let string = textView.text + text
        if string.utf16.count > maxWordsCount {
            textView.text = String(string.prefix(maxWordsCount))
            self.isLocationToEnd = isLocationToEnd
            return true
        }
        return false
    }
    
}
